<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Mail\OrderPost;
use App\Models\Order;
use App\Transformers\OrderTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class OrderController extends BaseController
{
    /**
     * 订单列表
     */
    public function index(Request $request)
    {
        //搜索订单编号
        $order_no = $request->input('order_no');
        //搜索收货人
        $trade_no = $request->input('trade_no');
        //搜索订单状态
        $status = $request->input('status');

        $orders = Order::when($order_no, function($query) use ($order_no) {
            $query->where('order_no', 'like', '%' . $order_no . '%');
        })->when($trade_no, function($query) use ($trade_no) {
            $query->where('trade_no', 'like', '%' . $trade_no . '%');
        })->when($status, function($query) use ($status) {
            $query->where('status', $status);
        })->paginate($request->size);
        return $this->response->paginator($orders, new OrderTransformer());
    }


    /**
     * 订单详情
     */

    public function show(Order $order)
    {
        return $this->response->item($order, new OrderTransformer());
    }

    /**
     * 发货
     */
    public function post(Request $request, Order $order)
    {
        $request->validate([
                               'express_type' => 'required|string|in:SF,YT,YD',
                               'express_no'   => 'required|string',
                           ], [
                               'express_type.required' => '请选择快递类型',
                               'express_type.in'       => '快递类型错误,只能是SF YT YD',
                               'express_no.required'   => '请输入快递单号',
                           ]);
        if ($order->status != 2) {
            return $this->response->errorBadRequest('订单状态错误,只能是支付状态');
        }

        //发货
        //$order->express_type = $request->input('express_type');
        //$order->express_no = $request->input('express_no');
        //$order->status = 3;
        //$order->save();
        //
        ////发货通知
        //Mail::to($order->user->email)->queue(new OrderPost($order));

        //使用事件辅助函数分发
        //event(
        //    new \App\Events\OrderPost(
        //        $order,
        //        $request->input('express_type'),
        //        $request->input('express_no')
        //    )
        //);

        //使用事件分发
        \App\Events\OrderPost::dispatch(
            $order,
            $request->input('express_type'),
            $request->input('express_no')
        );

        return $this->response->noContent();
    }

}
